import React, { useCallback, useEffect, useState, useRef } from 'react';
import { Button, Empty } from 'antd';
import classNames from 'classnames';
import { keyBy, take } from 'lodash';

import BizIcon from '@/components/BizIcon';

import SalaryItemCheck from '../SalaryItemCheck';
import styles from './index.less';

const ADD = 'add';
const LESS = 'less';

/**
 *
 * @param {string} [type = add | type= less]
 * @returns {JSX.Element}
 * @constructor
 */
const SalaryItemZoneHeader = ({ type }) => (
    <div className={styles.header}>
        {type === ADD ? (
            <>
                <BizIcon type="salary_add_icon" className={classNames(styles.icon, styles.add)} />
                薪资加项
            </>
        ) : null}
        {type === LESS ? (
            <>
                <BizIcon type="salary_minus_icon" className={classNames(styles.icon, styles.less)} />
                薪资减项
            </>
        ) : null}
    </div>
);

const SalaryItemZone = ({ type, list, selected, onChange, dataIndex, showMoreCount }) => {
    /** 展示的数据 */
    const [displayList, setDisplayList] = useState([]);
    /** 选择key： id, value: vo的map */
    const [selectedIdMap, setSelectedMap] = useState({});
    /** 选择的数据 */
    const [checkedList, setCheckedList] = useState([]);
    /** 收缩状态， true: 收缩, false: 展开 */
    const [collapsed, setCollapsed] = useState(true);
    /** 内容容器dom元素 */
    const contentElementRef = useRef(null);

    const handleChange = useCallback(
        ({ checked, item }) => {
            const newCheckList = checked ? [...checkedList, item] : checkedList.filter(data => data.id !== item.id);
            setCheckedList(newCheckList);
            onChange(newCheckList);
        },
        [onChange, checkedList]
    );

    useEffect(() => {
        setCheckedList(selected);
    }, [selected]);

    useEffect(() => {
        setSelectedMap(keyBy(checkedList, dataIndex));
    }, [checkedList, dataIndex]);

    useEffect(() => {
        if (!collapsed && contentElementRef.current) {
            // 此处用setTimeout是因为collapsed刚改变为false时，还不会出现滚动条，需渲染出滚动条后再设置scrollTop
            setTimeout(() => {
                // 滚动到下一行位置
                contentElementRef.current.scrollTop += 68;
            }, 0);
        }
    }, [collapsed])

    useEffect(() => {
        if (collapsed) {
            setDisplayList(take(list, showMoreCount));
        } else {
            setDisplayList(list);
        }
    }, [collapsed, list, showMoreCount]);

    return (
        <div className={styles.SalaryItemZone}>
            <SalaryItemZoneHeader type={type} />
            <div className={styles.content} ref={contentElementRef}>
                {displayList?.length > 0 ? (
                    displayList.map(item => (
                        <SalaryItemCheck
                            key={item.id}
                            item={item}
                            selected={!!selectedIdMap[item[dataIndex]]}
                            onChange={handleChange}
                        />
                    ))
                ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
            </div>
            {list?.length > showMoreCount && collapsed ? (
                <Button type="link" className={styles.more} onClick={() => setCollapsed(false)}>
                    更多
                    <BizIcon type="input-select-arrow-icon" className={styles.icon} />
                </Button>
            ) : null}
            {list?.length > showMoreCount && !collapsed ? (
                <Button type="link" className={styles.more} onClick={() => setCollapsed(true)}>
                    收起
                    <BizIcon type="input-select-arrow-icon" className={[styles.icon, styles.expand]} />
                </Button>
            ) : null}
        </div>
    );
};

SalaryItemZone.defaultProps = {
    list: [],
    selected: [],
    onChange: () => {},
    dataIndex: 'id',
    showMoreCount: 20
};

export default SalaryItemZone;
